package com.kly.cashmall.module.home.home_tab.tab_other;

import android.os.Handler;
import android.os.Looper;

/**
 * @author
 * @date 2018/1/18
 */
public class ObserverWrapper<T> implements ObserverInterface<T> {

  private ObserverInterface<T> observeInterface;

  public ObserverWrapper(ObserverInterface<T> observeInterface) {
    this.observeInterface = observeInterface;
  }

  public void handleChange() {
    handleChange(null);
  }

  @Override
  public void handleChange(final T t) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
      if (observeInterface != null) {
        observeInterface.handleChange(t);
      }
    } else {
      new Handler(Looper.getMainLooper()).post(() -> {
        if (observeInterface != null) {
          observeInterface.handleChange(t);
        }
      });
    }
  }

  public void registerObserve(int code, ObsRunnable<T> runnable) {
    registerObserve(String.valueOf(code), runnable);
  }

  @Override
  public void registerObserve(String code, ObsRunnable<T> runnable) {
    if (observeInterface != null) {
      observeInterface.registerObserve(code, runnable);
    }
  }

  public void unregisterObserve(int code) {
    unregisterObserve(String.valueOf(code));
  }

  @Override
  public void unregisterObserve(String code) {
    if (observeInterface != null) {
      observeInterface.unregisterObserve(code);
    }
    if (isEmpty()) {
      clear();
    }
  }

  @Override
  public boolean isEmpty() {
    return observeInterface == null || observeInterface.isEmpty();
  }

  @Override
  public void clear() {
    if (observeInterface != null) {
      observeInterface.clear();
    }
    observeInterface = null;
  }
}
